const express = require('express');
const cors = require('cors');

const app = express();
const port = process.env.PORT || 3050;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));  // Even I don't know what this line is for, two tutorials use that so I add it
app.use(cors());

const axios = require('axios');

const jwt = require("jwt-simple");

const get_chat_api = (password, func) => "https://openai.weixin.qq.com/openapi/nlp/"+func+"/ZomtB0FsfmJdB8DAllRzyXoA3aCu"+password[0]+password[1];

const get_jwt_data = (message, password) => {
  let payload = {
    uid: "test_user",
    data: {
      q: message,
    }
  }
  let encoding_key = "oUexWgSny3rTaPv7lzV7oKXGknJtPtZqNVVlzL5P3a"+password[2];
  let jwt_data = jwt.encode(payload, encoding_key);
  return jwt_data;
};

const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');

const assistant = new AssistantV2({
  version: '2022-03-08',
  authenticator: new IamAuthenticator({
    apikey: '9n6MokrcpuuU_vZXXDiEz1mkscUnE6m_QLIsHEOejfZN',
  }),
  serviceUrl: 'https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/a69986d8-49aa-4479-8207-5440def0e674',
});

const send_watson_message = async (message) => {
  try {
  let response = await assistant
  .messageStateless({
    assistantId: '5c2a7c0e-54bf-4bb6-9638-23292068fc84',
    input: {
      'message_type': 'text',
      'text': message,
    }
  });
  // console.log(response);
  // console.log(response.result.output.generic);
  return response.result.output.generic[0].text;
  }
  catch(e) { return "Unknown Error";}
};



const send_msg = async (message, password) => {
  const chat_api = get_chat_api(password, "casual_chat");
  const trans_api_2cn = get_chat_api(password, "translate_en2cn");
  const trans_api_2en = get_chat_api(password, "translate_cn2en");
  // const jwt_data = get_jwt_data(message, password);
  // const res = await axios.post(chat_api, {query: jwt_data});
  // if (res.data && res.data.response) {
  //   return res.data.response;
  // }
  // else {
  //   return "Unknown Error.";
  // }
  try {
    const res_cn = await axios.post(trans_api_2cn, {query: get_jwt_data(message, password)});
    const res_chat = await axios.post(chat_api, {query: get_jwt_data(res_cn.data.result, password)});
    const res_en = await(axios.post(trans_api_2en, {query: get_jwt_data(res_chat.data.response.slice(0, 10), password)}));
    // console.log("Data:", res_cn.data, res_chat.data, res_en.data);
    return res_en.data.result;
  }
  catch (err) {
    return "Unknown error.";
  }
};

// send_msg(process.argv.slice(2).join(" "), "BIX").then(res => console.log(res));
app.post("/chat", async (req, res) => {
  // let response = await send_msg(req.body.message, req.body.password);
  let response = await send_watson_message(req.body.message);
  return res.json({response});
});

app.listen(port, () => console.log(`App is on port ${port}`));